<template>
	<div v-drag>
		<div class="mask" @click="closePopup(false)"></div>
		<div class="edit_box" v-loading="loading">
			<div class="box_head">
				<p>{{ mid ? '修改' : '新增' }}商品</p>
				<i @click="closePopup(false)"></i>
			</div>
			<div class="box_body">

				<div class="line">
					<span class="lab"><i class="mark_icon">*</i>仓库：</span>
					<div :class="{'error_border':tip_num===1}">
						<el-select filterable placeholder="请选择仓库" v-model="warehouseId" value-key="id" :disabled="Boolean(wdata)">
							<el-option :key="item.id" :label="item.name" :value="item.id" v-for="(item,index) in warehouseList">
							</el-option>
						</el-select>
					</div>
				</div>

				<div class="line">
					<div class="g-mt-10">
						<a class="common_btn el-icon-delete" @click="clearNum()"></a>
						<a class="common_btn el-icon-circle-plus-outline" @click="addproNum()"></a>
					</div>
				</div>

				<div class="line" v-if="!mid">
					<!--<span class="lab"></span>-->
					<div :class="{'error_border':tip_num===2}" style="width: 100%">
						<div class="line_item" v-for="(item,index) in itemList">
							<div>
								<el-select filterable placeholder="请选择商品" v-model="itemList[index].productId" value-key="productId" @focus="resetProductId($event,index)">
									<!-- 动态数组 -->
									<template v-if="item.productId == ''">
										<el-option :key="item.id" :label="item.name" :value="item.id" v-for="(item,index) in productList">	</el-option>
									</template>
									<template v-else>
										<!-- 静态数组 -->
										<el-option :key="item.id" :label="item.name" :value="item.id" v-for="(item,index) in finalProductList">	</el-option>
									</template>
								</el-select>
							</div>
							<div>
								<!-- onKeypress="return(/[\d.]/.test(String.fromCharCode(event.keyCode)))" -->
								<el-input  placeholder="商品数" type="number" min="1"
								 v-model.number="itemList[index].numbers">
									<template slot="prepend">商品数</template>
								</el-input>
							</div>
							<div>
								<el-input placeholder="回收数" type="number" min="0"
								 v-model.number="itemList[index].returnNumber">
									<template slot="prepend">回收数</template>
								</el-input>
							</div>
							<!--只有一条的时候，不显示删除-->
							<span>
								<i @click="delVos(index)" class="el-icon-remove-outline delSingle"></i>
							</span>
						</div>
					</div>
				</div>
				<div class="line" v-if="mid">
					<span class="lab"><i class="mark_icon">*</i>商品：</span>
					<div :class="{'error_border':tip_num===2}">
						<el-select placeholder="请选择商品" v-model="productId">
							<el-option :key="item.id" :label="item.name" :value="item.id" v-for="(item,index) in productList">
							</el-option>
						</el-select>
					</div>
				</div>
				<div class="line" v-if="mid">
					<span class="lab"><i class="mark_icon">*</i>商品数量：</span>
					<div :class="{'error_border':tip_num===4}">
						<el-input type="number" placeholder="商品数量" min="1" v-model.number="numbers" @input="setTip('','')"></el-input>
					</div>
				</div>
				<div class="line" v-if="mid">
					<span class="lab"><i class="mark_icon">*</i>空桶数量：</span>
					<div :class="{'error_border':tip_num===5}">
						<el-input type="number" placeholder="空桶数量" v-model.number="returnNumber" min="0" @input="setTip('','')"></el-input>
					</div>
				</div>
				<p class="error_line">{{ infoTip }}</p>
			</div>
			<div class="box_foot">
				<span @click="closePopup(false)">取消</span>
				<span @click="confirmEdit">确定</span>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		getProductDetail,
		updateProduct,
		addProduct,
		delProduct,
		restProductList
	} from "@/api/basic/warehouse/product";
	import {
		getAllWarehouse,
		bindingProduct
	} from "@/api/basic/warehouse";
	import {
		listAllData
	} from "@/api/config/product";
	import {
		restUrl
	} from "../../../../url";
	import {
		getBtn
	} from "../../../utils/btnAuth";
	export default {
		props: ['mid', 'wdata'],
		data() {
			return {
				param: {
					folder: 'water'
				},
				uploadUrl: restUrl + '/common/upload',
				warehouseId: '',
				productName: '',
				productId: '',
				productPhoto: '',
				numbers: 0,
				returnNumber: 0,

				warehouseList: [],
				productList: [],
				finalProductList: [],
				isFinal:false,
				itemList: [{
					numbers: 1,
					productId: '',
					returnNumber: 0
				}],
				infoTip: '',
				tip_num: '',
				loading: false
			}
		},
		mounted() {
			let select = JSON.parse(localStorage.getItem('warehouse_select'));
			this.warehouseList = JSON.parse(localStorage.getItem('warehouse_select'));
			if (this.mid) {
				this.getDetail();
			} else {
				if (this.wdata) {
					this.warehouseId = this.wdata.id;
          this.getProduct();
				} else {
					if (select.length > 0) {
						this.warehouseId = this.warehouseList[0].id;
					}
					this.getProduct()
				}
			}

		},
		methods: {
			/*清除*/
			clearNum() {
				this.itemList = [];
				let cope = {
					numbers: 1,
					productId: '',
					returnNumber: 0
				}
				this.itemList.push(cope)
				this.tipText = '';
			},
			addproNum() {
				let cope = {
					numbers: 1,
					productId: '',
					returnNumber: 0
				}
				this.itemList.push(cope)
			},
			// 单个删除
			delSingleInput(index) {
				this.proNum.splice(index, 1);
				this.tipText = '';
			},

			showDel(index) {
				this.delNum = index + 1;
				/*只有一条的时候，不加删除文字，可清空*/
				if (this.proNum.length == 1) {
					this.delNum = null
				}
			},
			getDetail() {
				let that = this;
				this.loading = true;
				getProductDetail(this.mid).then(res => {
					that.setData(res);
					that.loading = false;
				}).catch((e) => {
					that.loading = false;
				});
			},


			//仓库列表
			warehouseData() {
				let that = this;
				getAllWarehouse('').then(res => {
					that.warehouseList = res ? res : [];
				}).catch((e) => {
					that.warehouseList = [];
				});
			},
			//根据仓库Id获取该仓库还没有的商品列表
			getProduct(data){
			  let queryParams = {
			    display:1,
          warehouseId: this.warehouseId,
			  };
			  if(data) {
			    queryParams.productIds = data;
			  }
        restProductList(queryParams).then((res)=>{
			    this.productList = res ? res: [];
			    if(!this.isFinal) {
			      this.finalProductList = res ? res :[];
			      this.isFinal = true;
			    }
			  })
			},
			//重置当前的id
			resetProductId(e,index) {
				this.itemList[index].productId = '';
				this.getNewAllProduct();
			},
			//获取已经当前已经选中的商品id数组
			getNewAllProduct() {
			  // 重新获取列表
			  let arr = []
			  this.itemList.forEach((item,index)=> {
			    if(item.productId != '') {
			      arr.push(item.productId)
			    }
			    return arr
			  })
			  arr = arr.join(',')
			  this.getProduct(arr);
			},

			//商品列表
			// getAllProduct() {
			// 	let that = this;
			// 	let queryParams = {
			// 		warehouseId: that.warehouseId,
			// 	};
			// 	restProductList(queryParams).then(res => {
			// 		that.productList = res ? res : [];
			// 	}).catch((e) => {
			// 		that.productList = [];
			// 	})
			// },

			// setData(obj) {
			// 	let defalutData = {
			// 		id: obj.productId,
			// 		name: obj.productName
			// 	}
			// 	this.productList.push(defalutData)
			// 	this.warehouseId = obj.warehouseId;
			// 	this.productName = obj.productName;
			// 	this.productId = obj.productId;
			// 	this.productPhoto = obj.productPhoto;
			// 	this.numbers = obj.numbers ? obj.numbers : 0;
			// 	this.returnNumber = obj.returnNumber ? obj.returnNumber : 0;
			// 	this.getAllProduct();
			// },

			// 确认编辑
			confirmEdit() {
				if (this.warehouseId === '') {
					this.setTip(1, '请选择仓库！');
				}
				this.judgeItemList();
			},

			sendInfo() {
				let that = this;
				that.loading = true;
				let data = {
					warehouseId: that.warehouseId,
				};
				if (that.mid) {
					data.id = that.mid;
					data.productId = that.productId;
					data.numbers = Number(that.numbers);
					data.returnNumber = Number(that.returnNumber);
					updateProduct(data).then(res => {
						that.closePopup(true);
						that.$message.success({
							message: '操作成功！',
							duration: 1500
						});
					}).catch((e) => {
						that.loading = false;
					});
				} else {
					data.bindingVos = that.itemList;
					bindingProduct(data).then(res => {
						that.closePopup(true);
						that.$message.success({
							message: '操作成功！',
							duration: 1500
						});
					}).catch((e) => {
						that.loading = false;
					});
				}
			},
			judgeItemList() {
				let dataLen = this.itemList.length;
				let index = dataLen -1;
				for(let i = 0;i < dataLen ;i++) {
					if(!this.itemList[i].productId) {
						this.errIndex = i;
						this.infoTip = '请选择商品或者删除不需要的商品!';
						return;
					}
					else {
						if(i == index) {
							//提交数据
							this.sendInfo();
						}
					}
				}

			},

			// isEnough(data) {
			// 	let num = 0;
			// 	let that = this;
			// 	for (let i = 0; i < data.length; i++) {
			// 		if (data[i].productId && data[i].numbers) {
			// 			num += data[i].numbers;
			// 		} else {
			// 			if (data.length > 1) {
			// 				that.delVos(i);
			// 				i--
			// 			}
			// 		}
			// 	}
			// 	return num;
			// },

			// 上传图标
			// avatarUpload(file) {
			// 	this.setTip('', '');
			// 	this.loading = true;
			// 	const isLt10M = file.size / 1024 / 1024 < 10;
			// 	if (!isLt10M) {
			// 		this.$message.error({
			// 			message: '上传图像大小不能超过 10MB!',
			// 			duration: 1500
			// 		});
			// 	}
			// 	return isLt10M;
			// },

			// // 图标上传回调
			// avatarSuccess(res, file) {
			// 	if (file.response.success) {
			// 		this.productPhoto = file.response.data;
			// 		this.$message.success({
			// 			message: '上传成功！',
			// 			duration: 1500
			// 		});
			// 	} else {
			// 		this.$message.error({
			// 			message: '上传失败，请重试',
			// 			duration: 1500
			// 		});
			// 	}
			// 	this.loading = false;
			// },

			delVos(index) {
				this.itemList.splice(index, 1)
			},


			// 关闭
			closePopup(refresh) {
				this.$emit('listenToChild', {
					refresh: refresh
				})
			}
		}
	}
</script>

<style scoped>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #60BAE7;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #DCDFE6;
		width: 100px;
		height: 100px;
		line-height: 100px;
		text-align: center;
		border: 1px solid #DCDFE6;
		border-radius: 6px;
	}

	.avatar {
		max-width: 210px;
		min-width: 60px;
		height: 100px;
		display: block;
		border-radius: 6px;
		margin-right: 15px;
		border: 1px solid #bbb;
	}

	.line_item {
		display: flex;
		justify-content: space-around;
		align-items: center;
		margin-bottom: 10px;
		width: 100%;
	}

	.line .line_item>div {
		width: 27% !important;
	}

	.line .line_item>span {
		display: block;
		width: 30px;
	}

	.line .line_item i,
	.addlist {
		font-size: 25px;
		color: #6687f9;
		cursor: pointer;
	}

	.common_btn {
		font-size: 24px;
		cursor: pointer;
		color: #6687f9;
		margin-right: 5px;
	}

	.delSingle {
    color: #e40000 !important;
	}
</style>
